package com.example.testdemoutils.dynamic_data_source.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.example.testdemoutils.dynamic_data_source.utils.DynamicDBUtil;
import com.example.testdemoutils.dynamic_data_source.utils.SpringContextUtils;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 多数据源
 */

public class DynamicDataSource extends AbstractRoutingDataSource {

    public static Map<Object, Object> targetDataSources = new ConcurrentHashMap<>(10);

    @Override
    protected Object determineCurrentLookupKey() {
        return DynamicContextHolder.peek();
    }

    public static void setDataSource(String dbKey) {
        if (!DynamicDataSource.targetDataSources.containsKey(dbKey)) {
            DruidDataSource dataSource = DynamicDBUtil.getDbSourceByDbKey(dbKey);
            DynamicDataSource.targetDataSources.put(dbKey, dataSource);
        }
        //切换动态多数据源的dbKey
        DynamicContextHolder.push(dbKey);
        DynamicDataSource dynamicDataSource = (DynamicDataSource) SpringContextUtils.getBean("dynamicDataSource");
        dynamicDataSource.setTargetDataSources(targetDataSources);
        //使得修改后的targetDataSources生效
        dynamicDataSource.afterPropertiesSet();
    }

}


